// require('./execute/getModel'); // 创建翻译文件
const dataAccess = require('./dataAccess');
const fs = require('fs');
const sysModel = dataAccess["main"].model("sysModel");
const sysModelView = dataAccess["main"].model("sysModelView");
var modelCodes = require('./config').modelCodes;



async function main(){
    for (var i = 0; i < modelCodes.length; i++) {
        var modelList = await sysModel.findAll({
            "include": sysModel.getFullReferences(),
            "where": {
                "modelCode": modelCodes[i]
            },
        });
        modelList.forEach(function(element,index){
            var model = element.get({ plain: true });
            exec(model);
        });
    }
}

async function exec(sysModel){
    try{
        var modelCode = sysModel.modelCode;
        var modelFileName = sysModel.modelAlName.charAt(0).toLowerCase() + sysModel.modelAlName.slice(1);
        
        var modelPath = mkdirByPath(modelFileName);
        var sysModelViewList = await getView(modelCode);
        var modelMes = await getModel(modelCode);
        for(var i = 0; i < sysModelViewList.length; i++){
            var view = sysModelViewList[i];
            
            if(view.configType == "query" || view.configType == "tableView"){
                var obj = JSON.parse(view.content);
                obj.elements.forEach(item=>{
                    item.label = item.remark;
                    if(view.configType == "query"){
                        item.props={
                            disabled: item.disabled,
                            placeholder:  item.componentName=='xSelect'?'请选择'+item.remark:'请输入'+item.remark,
                            maxlength: item.maxlength,
                            minlength: item.minlength || null,
                            showWordLimit: item.showWordLimit || null,
                            rows: item.rows || null,
                            clearable: true
                        }
                    }
                    if(view.configType == "tableView"){
                        if(item.filter){
                            item.filter={
                                funcName: item.filter,
                                optionKey: item.filterArgs || item.attrName
                            }
                        }
                        
                    }
                    item.placeholder = undefined;
                    item.disabled = undefined;

                })
                var jsStr = "export default{\n\t";
                jsStr += '"renderClass":"' + view.renderClass + '",\n\t';
                jsStr += '"elements":' + JSON.stringify(obj.elements,null, 4);
                jsStr += '\n}'
                var name = view.configType + ".js"
                writeJsFile(modelPath + "/" + name, jsStr)
                console.log(name,"已完成")
            }else{
                var obj = JSON.parse(view.content);
                obj.renderClass = view.renderClass;
                obj.elements.forEach(item=>{
                    item.label = item.remark;
                    item.props={
                        disabled: item.disabled,
                        placeholder: item.componentName=='xSelect'?'请选择'+item.remark:'请输入'+item.remark,
                        maxlength: item.maxlength,
                        minlength: item.minlength || null,
                        showWordLimit: item.showWordLimit || null,
                        rows: item.rows || null,
                        clearable: true,
                    }
                    if(item.ruleList && item.ruleList.length>0){
                        item.ruleList.forEach(rule=>{
                            if(rule.required){
                                rule.message = '请输入' + item.remark;
                            }
                        })
                    }
                    
                    item.placeholder = undefined;
                    item.disabled = undefined;
                    item.span=24;
                })
                var jsStr = "export default\n\t";
                jsStr += JSON.stringify(obj, null,4);
               
                var name = view.configType + ".js"
                
                writeJsFile(modelPath + "/" + name, jsStr)
                console.log(name,"已完成")
            }
                
               
        }
 var jsStr2 = `export default[
    {
        actionPage: "showAddModal",
        actionType: "2",
        code:'add',
        commandArgs: "",
        commandCode: "SaveNew",
        icon :  "add",
        mSelectFlag :  "0",
        selectFlag :  "0",
        name: "新增",
        titleText: "新增${modelMes.modelName}"
    },
    {
        actionPage: "showAddModal",
        actionType: "2",
        code:'edit',
        commandArgs: "",
        commandCode: "Update",
        icon :  "edit",
        mSelectFlag :  "0",
        selectFlag :  "1",
        name: "编辑",
        titleText: "编辑${modelMes.modelName}"
    },
    {
        actionPage: "NONE",
        actionType: "3",
        code:'delete',
        commandArgs: "",
        commandCode: "Delete",
        icon :  "delete",
        mSelectFlag :  "1",
        selectFlag :  "1",
        name: "删除",
        confirmMsg: "确认删除？"
    },
     {
        actionPage: "showDetailModal",
        actionType: "2",
        code:'viewData',
        commandArgs: "",
        commandCode: "NONE",
        icon :  "view",
        mSelectFlag :  "0",
        selectFlag :  "1",
        name: "查看",
        titleText: "查看${modelMes.modelName}"
    },
]`
        var name2 = "button.js"
        writeJsFile(modelPath + "/" + name2, jsStr2)
        console.log(name2,"已完成")
        
        var vueFile = 
`<template>
    <div class="${modelFileName}">
        <xCommonView :menuinfo="menuinfo" :uiConfig="uiConfig" v-if="isInit"/>
    </div>
    </template>
<script>
    import pageMixin from "@/mixins/pageMixin"
    import queryConfig from "./query.js"
    import viewConfig from "./detail.js"
    import editConfig from "./edit.js"
    import tableConfig from "./tableView.js"
    import addConfig from "./add.js"
    import buttonConfig from "./button.js"
    export default{
        name: '${modelFileName}',
        mixins: [pageMixin],
        data(){
            return{
                uiConfig:{
                    query:queryConfig,
                    table:tableConfig,
                    add:addConfig,
                    edit:editConfig,
                    view:viewConfig,
                    button:buttonConfig
                }
            }
        },
        mounted(){
            
        }
    }
</script>

<style lang="scss">

</style>`
        // 生成vue文件
        writeJsFile(modelPath + "/" + "index.vue", vueFile)
        console.log("index.vue","已完成")
    }catch(e){
        console.log(e);
    }
    console.log("Done");
}


function writeJsFile(modelPath, indexStr) {
    fs.writeFile(modelPath, indexStr, (err, data) => {
        if (err) {
            console.log(err);
        }
    })
}

async function getModel(code){
    var modelList = await sysModel.findAll({
        "include": sysModel.getFullReferences(),
        "where": {
            "modelCode": code
        },
    });
    return modelList[0];
}


async function getView(code){
    var sysModelViewList = await sysModelView.findAll({
        "where": {
            "modelCode": code
        },
    });
    return sysModelViewList;
}


function mkdirByPath(dirName) {
    const FilePath = "./model/" + dirName;
    // 新建的类的长度大于1，需要新建model文件夹
    if (!fs.existsSync(FilePath)) {
        fs.mkdirSync(FilePath)
        return FilePath;
    } else {
        // deleteDir(FilePath)
        // fs.mkdirSync(FilePath)
        return FilePath;
    }
}

main();